package com.iflytek.uoamp.notify.wechat.format;

import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.iflytek.uoamp.common.notify.enumerate.State;
import com.iflytek.uoamp.common.notify.exception.NotifyException;
import com.iflytek.uoamp.common.notify.obj.BaseInfo;
import com.iflytek.uoamp.common.notify.obj.BizInfo;
import com.iflytek.uoamp.common.notify.obj.Content;
import com.iflytek.uoamp.common.notify.obj.MonitorInfo;
import com.iflytek.uoamp.common.notify.obj.Notification;
import com.iflytek.uoamp.common.notify.util.NotifyUtils;

public class FormatBizWecaht extends FixedWechatFormatter {
	
    private static final String BIZ = "业务";
    private static final String TIME_FORMAT = "yyyy-MM-dd-HH:mm";

    @Override
    public String pretty(Notification notification, List<?> contents) throws NotifyException{
        Content content = getMostCritical(contents);
        StringBuilder builder = new StringBuilder(TEMPLATE_ID + "@@");
        builder.append("{\"monitortime\":\"");
        builder.append(content.getMonitorTime());
        
        builder.append("\",\"monitortype\":\"");
        builder.append(BIZ);
        
        builder.append("\",\"monitorname\":\"");
        MonitorInfo monitorInfo = content.getMonitorInfo();
        String output = content.getOutput();
        if(StringUtils.isNotEmpty(output)&&output.contains("[")&&output.contains("]")){
        	builder.append(output.substring(output.indexOf("["), output.indexOf("]")+1));
        }
        BaseInfo baseInfo = monitorInfo.getBaseInfo();
        if(baseInfo != null && StringUtils.isNotEmpty(baseInfo.getIP())){
        	builder.append("("+baseInfo.getIP()+")"+getMonitorName(monitorInfo));
        }
        else {
        	builder.append(getMonitorName(monitorInfo));
		}
        
        builder.append("\",\"state\":\"");
        builder.append(State.getName(content.getState()));
        
        builder.append("\",\"statedes\":\"");
        if("success".equals(content.getState())){
        	builder.append("响应时间恢复正常！" + getMonitorPtName(contents));
        }
        else {
        	builder.append(NotifyUtils.getAttributeValue(content.getOutput(),"statedes") + getMonitorPtName(contents));
		}
        builder.append("\"}");
        
        return builder.toString();
    }
    
    private String getMonitorName(MonitorInfo monitorInfo) {
        if(monitorInfo == null) {
            return "";
        }
        
        StringBuilder builder = new StringBuilder();
        BizInfo bizInfo = monitorInfo.getBizInfo();
        
        if(bizInfo != null && !StringUtils.isBlank(bizInfo.getBizName())) {
            builder.append(bizInfo.getBizName());
        }
        
        return builder.toString();
    }
    
    private String getMonitorPtName(List<?> contents) {
        StringBuilder pointName = new StringBuilder();
        for(Object item : contents) {
            Content content = (Content)item;
            pointName.append(content.getMonitorInfo().getBizInfo().getMonitorptName());
            pointName.append(",");
        }
        NotifyUtils.deleteLast(pointName, ',');
        
        return MessageFormat.format("({0})", pointName);
    }
    
    /**
     * 获取多个cotent中等级最严重且时间位于最近时间点的cotent,注意，这里不需要判断contents
     * 是否为空,原因是该函数由SendMsgAction中的sendMsg调用,sendMsg能够保证传入的列表不为空
     * @param contents cotent列表
     * @return
     * @throws NotifyException
     */
    private Content getMostCritical(List<?> contents) throws NotifyException{
        int stateValue = -1;
        int index = -1;
        String lastTime = null;
        
        for(Object item : contents) {
            Content content = (Content)item;
            State state = State.getState(content.getState());
            if(state.getID() > stateValue || ((state.getID() == stateValue 
                    && timeDiff(content.getMonitorTime(), lastTime) > 0))) {
                index = contents.indexOf(item);
                lastTime = content.getMonitorTime();
                stateValue = state.getID();
            }
        }
        
        return (Content)contents.get(index);
    }
    
    private int timeDiff(String firstStr, String secondStr) throws NotifyException{
        SimpleDateFormat formatter = new SimpleDateFormat(TIME_FORMAT);
        Date firstDate, secondDate;
        try {
            firstDate = formatter.parse(firstStr);
            secondDate = formatter.parse(secondStr);
        } catch (ParseException e) {
            throw new NotifyException(e.getMessage());
        }
        return firstDate.compareTo(secondDate);
    }
}
